<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>封装ajax_纯回调</title>
	</head>
	<body>
		<!-- 
				定义一个sendAjax函数，对xhr的GET请求进行封装，该函数接收1个配置对象：
						配置对象中包含如下四个属性：
								url(请求地址)
								data(参数)
								success(成功的回调)
								error(失败的回调)
		-->
		<script type="text/javascript" >
			function sendAjax(options){
				//获取请求相关的参数
				const {url,data,success,error} = options
				//创建xhr
				const xhr = new XMLHttpRequest()
				//绑定监听
				xhr.onreadystatechange = ()=>{
					if(xhr.readyState === 4 ){
						if(xhr.status >= 200 && xhr.status <= 299) success(xhr.response)
						else error(xhr.response)
					}
				}
				//自动解析json
				xhr.responseType = 'json'
				let str = ''
				for (let key in data){
					str += `${key}=${data[key]}&`
				}
				str = str.slice(0,-1)
				//配置请求信息
				xhr.open('GET',url+'?'+str)
				//发送请求
				xhr.send()
			}
			
			sendAjax({
				url:'https://api.apiopen.top/getJoke',
				data:{count:30,type:'video'},
				success(data){
					console.log(data)
				},
				error(e){
					console.log(e)
				}
			})
		</script>
	</body>
</html>